package com.chb.common;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.chb.MybatisProjectMain;
import com.chb.config.GeneratorConfig;

import java.io.File;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: CHB
 * @create: 2021-10-22 14:04
 **/
public class MySqlGenerator {
    public static void main(String[] args) {
        // 代码生成器
        GeneratorConfig generatorConfig = new GeneratorConfig();
        // 工程名称
        String projectName = "mybatis";
        String projectPath = System.getProperty("user.dir");
        generatorConfig.setOutputDir(projectPath + "/" + projectName);
        // 作者
        generatorConfig.setAuthor("CHB");
        // 数据库地址
        generatorConfig.setUrl("jdbc:mysql://localhost:3306/boot_demo?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false");
        // 用户名
        generatorConfig.setUsername("root");
        // 密码
        generatorConfig.setPassword("123456");
        // 模块名称
       // generatorConfig.setModuleName("");
        // 父路径
        generatorConfig.setParent(MybatisProjectMain.class.getPackageName());
        // 要生成的表集合
        generatorConfig.setIncludeTables(new String[]{"t_ceeshi"});
        // 表前缀
        generatorConfig.setTablePrefix("t_");

        run(generatorConfig);
    }

    public static void run(GeneratorConfig generatorConfig) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        // 生成基本的resultMap
        gc.setBaseResultMap(true);
        // 生成基本的SQL片段
        gc.setBaseColumnList(true);
        gc.setOutputDir(generatorConfig.getOutputDir() +  "/src/main/java");
        // 作者名称
        gc.setAuthor(generatorConfig.getAuthor());
        gc.setOpen(false);
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sService");

        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(generatorConfig.getUrl());
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername(generatorConfig.getUsername());
        dsc.setPassword(generatorConfig.getPassword());
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(generatorConfig.getModuleName());
        pc.setParent(generatorConfig.getParent());

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude(generatorConfig.getIncludeTables());
        strategy.setControllerMappingHyphenStyle(false);
        strategy.setTablePrefix(generatorConfig.getTablePrefix());
     //   strategy.setSuperEntityClass("com.fivestar.ssp.common.mybatisplus.entity.BaseEntity");
    //    String[] superEntityColumns = {"create_time", "create_user", "create_user_name", "update_time", "update_user", "update_user_name", "status", "is_deleted"};
    //    strategy.setSuperEntityColumns(superEntityColumns);
        // 自定义 controller 父类
   //     strategy.setSuperControllerClass("com.fivestar.ssp.common.core.base.controller.BaseController");
        mpg.setStrategy(strategy);
        // 选择 freemarker 引擎需要指定如下加，注意 pom 依赖必须有！
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        customPackagePath(pc, mpg, generatorConfig);
        mpg.execute();
    }

    public static void customPackagePath(PackageConfig pc,AutoGenerator mpg, GeneratorConfig generatorConfig) {

        String projectPath = generatorConfig.getOutputDir();
        String mavenPath = "/src/main/java/";
        String srcPath = projectPath + mavenPath;

        String moduleName = pc.getModuleName();

        /**
         * packageInfo配置controller、service、serviceImpl、entity、mapper等文件的包路径
         * 这里包路径可以根据实际情况灵活配置
         */
        Map<String,String> packageInfo = new HashMap<>(16);

        packageInfo.put(ConstVal.CONTROLLER, generatorConfig.getParent() + ".controller");
        packageInfo.put(ConstVal.SERVICE, generatorConfig.getParent() + ".service");
        packageInfo.put(ConstVal.SERVICE_IMPL, generatorConfig.getParent() + ".service");
        packageInfo.put(ConstVal.ENTITY, generatorConfig.getParent() + ".entity");
        packageInfo.put(ConstVal.MAPPER, generatorConfig.getParent() + ".mapper");

        /**
         * pathInfo配置controller、service、serviceImpl、entity、mapper、mapper.xml等文件的生成路径
         * srcPath也可以更具实际情况灵活配置
         * 后面部分的路径是和上面packageInfo包路径对应的源码文件夹路径
         * 这里你可以选择注释其中某些路径，可忽略生成该类型的文件，例如:注释掉下面pathInfo中Controller的路径，就不会生成Controller文件
         */
        Map<String, String> pathInfo = new HashMap<>(16);
        pathInfo.put(ConstVal.CONTROLLER_PATH, srcPath + packageInfo.get(ConstVal.CONTROLLER).replace(".", File.separator));
        pathInfo.put(ConstVal.SERVICE_IMPL_PATH, srcPath + packageInfo.get(ConstVal.SERVICE_IMPL).replace(".", File.separator));
        pathInfo.put(ConstVal.SERVICE_PATH, srcPath + packageInfo.get(ConstVal.SERVICE).replace(".", File.separator));
        pathInfo.put(ConstVal.ENTITY_PATH, srcPath + packageInfo.get(ConstVal.ENTITY).replace(".", File.separator));
        pathInfo.put(ConstVal.MAPPER_PATH, srcPath + packageInfo.get(ConstVal.MAPPER).replace(".", File.separator));
        pathInfo.put(ConstVal.XML_PATH, projectPath+"/src/main/resources/mapper/");
        pc.setPathInfo(pathInfo);
        mpg.setPackageInfo(pc);
        /**
         * 创建configBuilder对象，传入必要的参数
         * 将以上的定义的包路径packageInfo配置到赋值到configBuilder对象的packageInfo属性上
         * 因为packageInfo是私有成员变量，也没有提交提供公共的方法，所以使用反射注入
         */
        ConfigBuilder configBuilder = null;
        try {
            configBuilder = new ConfigBuilder(mpg.getPackageInfo(), mpg.getDataSource(), mpg.getStrategy(), mpg.getTemplate(), mpg.getGlobalConfig());
            Field packageInfoField = configBuilder.getClass().getDeclaredField("packageInfo");
            packageInfoField.setAccessible(true);
            packageInfoField.set(configBuilder,packageInfo);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        /**
         * 设置配置对象
         */
        mpg.setConfig(configBuilder);
    }
}
